package com.sean.server.controller;

import java.io.IOException;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sean.server.service.UploadService;

@Controller
public class UploadController {
	
	@Autowired
	private UploadService uploadService;
	
	@RequestMapping(value = "/index")  
    public String index(String p) throws IOException {  
		if(uploadService.auth(p)) {
			return "index";  
		}
		return null;
    }
	
	@ResponseBody
	@RequestMapping(value = "/upload")  
    public String upload(HttpServletRequest request, ModelMap model) throws IOException {  
		ServletInputStream is = request.getInputStream();
		uploadService.save(is);
        return uploadService.isUpload();  
    }
	
	@ResponseBody
	@RequestMapping(value = "/isdownload")  
    public String isDownload(String p) throws IOException { 
		if(uploadService.auth(p)) {
			return uploadService.isDownload();  
		}
		return null;
    }
	
	@ResponseBody
	@RequestMapping(value = "/isupload")  
    public String isUpload() throws IOException {  
        return uploadService.isUpload();
    }
	
	@RequestMapping(value = "/download")
    public void download(HttpServletRequest request, HttpServletResponse response, String p) throws IOException {
		if(uploadService.auth(p)) {
			response.setContentType("text/html;charset=utf-8");   
	        request.setCharacterEncoding("UTF-8");
	        response.setContentType("application/x-msdownload;");   
	        response.setHeader("Content-disposition", "attachment; filename=temp.jpg");   
	        uploadService.download(response.getOutputStream());
		}
    }
}
